package com.tanhua.server.Controller;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.UserInfo;
import com.tanhua.server.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/loginReginfo")
    public void loginReginfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token){
        //1.判断token
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken){
            throw new RuntimeException("用户未登录");
        }

        //2.解析token（获取用户ID）
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);

        //3.将用户id设置到info对象
        userInfo.setId(id);

        //4.调用service保存
        userService.saveUserInfo(userInfo);

    }

    //上传用户图像
    @PostMapping("/loginReginfo/head")
    public void head(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        //1. 判断token里的数据是否存在
        boolean verifyToken = JwtUtils.verifyToken(token);

        //2. 若不存在就抛出异常
        if (!verifyToken){
            throw new RuntimeException("用户未登录");
        }

        //3. 若存在的话，调用方法保存
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);
        userService.head(id,headPhoto);

    }

}
